import storejs from 'storejs';
import api from '@/api/index.js';
import router from '@/router/index.js';
import {userKeys, hasLogin} from '@/utils/authUtils.js';

const keys = userKeys;

// 用户状态
const state = {
    //token信息
    tokenInfo: storejs.get(keys.tokenInfo),
    //当前token字符串
    token: storejs.get(keys.token),
    //用户信息
    userInfo: storejs.get(keys.userInfo),
}


const getters = {

}

const mutations = {
    setTokenInfo(state, tokenInfo){
        let token = tokenInfo.value;
        state.tokenInfo = tokenInfo;
        state.token = token;

        // 保存到本地
        storejs.set(keys.token, token);
        storejs.set(keys.tokenInfo, tokenInfo);
    },
    setUserInfo(state, userInfo){
        state.userInfo = userInfo;
        storejs.set(keys.userInfo, userInfo);
    },
}

const actions = {
    /**
     * 登录
     */
    login(context, formData){
        return new Promise((resolve, reject) => {
            api.sysUser.login(formData).then(res=>{
                let data = res.data;
                // 保存至state状态
                context.commit('setTokenInfo', data.tokenInfo);
                context.commit('setUserInfo', data.userInfo);
                resolve(res);
            }).catch(e=>{
                reject(e);
            });
        });
    },
    /**
     * 注销登录
     */
    loginout(context){
        return new Promise((resolve, reject) => {
            api.sysUser.logout().then(res=>{
                resolve(res);
                logout();
            }).catch(e=>{
                reject(e);
                logout();
            });
        });
    },
    /**
     * 获取个人信息
     */
    getUserInfo(context){
        return new Promise((resolve, reject) => {
            if (!hasLogin()) {
                return reject("未登录");
            }
            api.sysUser.currentUserInfo().then(res=>{
                let data = res.data;
                context.commit('setUserInfo', data);
                resolve(res);
            }).catch(e=>reject(e));
        });
    },
};

/**
 * 注销登录
 * @param context state上下文
 */
function logout(context) {
    // 清除缓存
    storejs.remove(keys.token);
    storejs.remove(keys.tokenInfo);
    storejs.remove(keys.userInfo);

    if (context) {
        context.state.token = null;
        context.state.tokenInfo = null;
        context.state.userInfo = null;
        context.state.orgInfo = null;
    }

    //当前路由
    let currentRoute = router.currentRoute;

    let route = router.resolve({
        name: 'login',
        query: {
            redirectPath: encodeURIComponent(currentRoute.fullPath)
        },
    });
    window.location.href = route.href;
    // window.location.reload();
    // window.open(route.href);
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}
